package com.example.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

//定义数据库封装类
public class DBUtil {
    private static Connection conn;
    private static Statement stmt;
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.建立与数据库的链接
            String url = "jdbc:mysql://localhost:3306/eshop?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
            String user = "root";
            String pwd = "1625344721Qq@";
            conn = DriverManager.getConnection(url, user, pwd);
            stmt  = conn.createStatement();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    // 获取数据库连接
    public static Connection getConnection() throws Exception {
        return conn;
    }

    //1.查询
    public static ResultSet query(String sql) throws Exception{
        return stmt.executeQuery(sql);
    }

    //2.更新
    public static int update(String sql)  throws Exception{
       return stmt.executeUpdate(sql);
    }

    //3.关闭连接
    public  static  void close(){
        try {
            stmt.close();
            conn.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
